/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 07 - 10
 * Time: 11:46
 */
//力扣 2.两数相加
class ListNode {
      int val;
    ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
class Solution1 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);//相当于创建一个新的链表
        ListNode cur = pre;
        int carry = 0;
        while((l1 != null) || (l2 != null)) {//注意条件用的是||
            int x = (l1 == null ? 0 : l1.val);
            int y = (l2 == null ? 0 : l2.val);
            int sum = x + y + carry;
            carry = sum / 10;
            int leave = sum % 10;
            cur.next = new ListNode(leave);
            cur = cur.next;
            if(l1 != null) {
                l1 = l1.next;
            }
            if(l2 != null) {
                l2 = l2.next;
            }
        }
        if(carry == 1) {//不要漏了这一步
            cur.next = new ListNode(carry);
        }
        return pre.next;
    }
}
